import { reqSendCode, reqUserRegister, reqUserLogin, reqUserToken,reqLoginOut } from "@/api"
// 引入uuid
import { setToken,removeToken } from "@/utils/token"
// 登陆和注册的仓库
const actions = {
    // 验证码
   async getCode({commit},phone) {
      let result = await reqSendCode(phone)
    //   console.log(result);
    if(result.code == 200) {
        commit('CODE',result.data) 
        return 'ok'
    } else {
        return Promise.reject(new Error('验证码接口出错了'))
    }
    },
    // 注册
   async postUserRegister({commit},data) {
       let result = await reqUserRegister(data)
       if(result.code == 200) {
        return 'ok'
       } else {
        Promise.reject(new error(result.message))
       }
    },
    // 登陆
   async userLogin({commit},data) {
        let result = await reqUserLogin(data)    
        // console.log(result);
        if(result.code == 200) {
            // 用户已经登陆成功且获取到token
            commit('USERLOGIN',result.data.token)
            // 本地持久化存储token
            // localStorage.setItem("TOKEN",result.data.token)
            // setToken(result.data.token)
            // 持久化存储token
            setToken(result.data.token)
            return 'ok'
        } else {
            return Promise.reject(new Error(result.message))
        }
    },
    // 用户的token信息
   async userInfo({commit}) {
        let result = await reqUserToken()
        // console.log(result);
        if(result.code == 200) {
            commit('USERINFO',result.data)
            return 'ok'
        }
    },
    // 退出登陆
   async getLoginOut({commit}) {
       let result = await reqLoginOut() 
       if(result.code== 200) {
        commit('CLEAR')
        return 'ok'
       } else {
        return Promise.reject(new Error(result.data))
       }
    }
    
}
const mutations = {
    CODE(state,code) {
        state.code = code
    },
    USERLOGIN(state,token) {
        state.token = token
    },
    USERINFO(state,userInfo) {
        state.userInfo = userInfo
    },
    CLEAR(state) {
        state.userInfo = {},
        state.token = '',
        removeToken()
    }
}
const state = {
    // 验证码
    code:'',
    // 唯一标识  持久化存储token
    token: localStorage.getItem('TOKEN'),
    // 用户名
    nickName:'',
    userInfo:{}
}

const getters = {

}
export default {
    actions,
    mutations,
    state,
    getters
}